'''
Created on 2011-10-30

@author: tony.li.fly@gmail.com
'''
from xyh.oa.models import User,Role
from django.http import HttpResponse
from django.utils import simplejson as json
from xyh.oa.utils.utils import Encoder
import datetime
def listall(request):
    result = []
    for c in User.objects.order_by('name').all():
        result.append({'id':c.id,'name':c.name,'password':c.password,'activable':c.activable,'insert_date':c.insert_date})
    return HttpResponse(json.dumps(result,cls=Encoder))

def addUser(request):
    if request.POST['name'] == 'admin':
        raise Exception 
    activable = True if request.POST['activable']=='true' else False
    user = User(name=request.POST['name'], password=request.POST['password'], activable=activable,insert_date = datetime.datetime.now())
    user.save()
    return HttpResponse()
def updateUser(request):
    user = User.objects.get(pk=request.POST['id'])
    user.name = request.POST['name']
    user.password = request.POST['password']
    activable = True if request.POST['activable']=='true' else False
    user.activable = activable
    user.save()
    return HttpResponse()

def roleConfig(request):
    userId = request.POST['userId']
    user = User.objects.get(pk=userId)
    checked_roles = []
    for i in user.roles.all():
        checked_roles.append(i.id)
   
    _roles = []
    for _role in Role.objects.all():
        if checked_roles.__contains__(_role.id):
            _roles.append({"id":_role.id,"name":_role.name,"checked":True})
        else:
            _roles.append({"id":_role.id,"name":_role.name})
    return HttpResponse(json.dumps(_roles))

def resetRoleConfig(request):
    userId = request.POST['id']
    roles = request.POST.getlist('roles')
    user = User.objects.get(pk=userId)
    user.roles.clear()
    for role_id in roles:
        user.roles.add(Role.objects.get(pk=role_id))
    return HttpResponse()